package hn.cch.advanced.concurrent.atomic;

import hn.cch.advanced.concurrent.ExecutorServiceDemo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerDemo {

    private static final Logger logger = LoggerFactory.getLogger(AtomicIntegerDemo.class);


    private Integer integer;
    private AtomicInteger atomic;

    public void runUnsafe(int cost) {
        integer -= cost;
    }

    public void runAtomic(int cost) {
        // int prev, next;
        // do {
        //     prev = atomic.get();
        //     next = prev - cost;
        // } while (!atomic.compareAndSet(prev, next)); // 循环判断设置
        // 简化代码
        atomic.addAndGet(-cost);
    }

    public static void main(String[] args) {

        int init = 100000;
        int cost = 10;
        AtomicIntegerDemo demo = new AtomicIntegerDemo();
        demo.integer = init;
        for (int i = 0; i < init / cost; i++) {
            demo.runUnsafe(cost);
        }
        logger.debug("result:{}", demo.integer);

        demo.integer = init;
        demo.atomic = new AtomicInteger(init);

        int n = 3;
        ExecutorService threadPool = Executors.newFixedThreadPool(n);
        for (int i = 0; i < init / cost; i++) {
            threadPool.execute(() -> demo.runUnsafe(cost));
            threadPool.execute(() -> demo.runAtomic(cost));
        }

        threadPool.shutdown();
        ExecutorServiceDemo.complete(threadPool);
        logger.debug("integer:{}", demo.integer);
        logger.debug("atomic:{}", demo.atomic.get());


    }


}
